package core

import (
	"container/list"
	"gitee.com/cooge/impush/user"
	log "github.com/sirupsen/logrus"
	"time"
)

type AddHandlerFunc func(string, interface{})

type DeleteHandlerFunc func(string, interface{},*time.Time)

type FilterHandlerFunc struct {
	addHandlerFunc    AddHandlerFunc
	deleteHandlerFunc DeleteHandlerFunc
}

func NewFilterHandlerFunc(addHandlerFunc AddHandlerFunc, deleteHandlerFunc DeleteHandlerFunc) *FilterHandlerFunc {
	var filterHandlerFunc FilterHandlerFunc
	filterHandlerFunc.addHandlerFunc = addHandlerFunc
	filterHandlerFunc.deleteHandlerFunc = deleteHandlerFunc
	return &filterHandlerFunc
}

var filterlist = list.New()

func AddFilter(fhf *FilterHandlerFunc) {
	filterlist.PushBack(fhf)
}

func AddUser(userid string, value interface{}) {

	log.Debug("添加新用户",userid)

	if len(userid) > 0 {
		nl := user.AddUser(userid, value)
		if nl && filterlist.Len() > 0 {

			log.Debug("添加新用户",userid,"进入过滤器")

			for e := filterlist.Front(); e != nil; e = e.Next() {
				fh, ok := e.Value.(*FilterHandlerFunc)
				if ok {
					fh.addHandlerFunc(userid, value)
				}
			}
		}
	}
}


func GetUser(userid string) []interface{} {
	return user.GetUsers(userid)
}
func GetUserAddTime(userid string) *time.Time {
	return user.GetUserAddtime(userid)
}


func GetALLUsers() []string {
	return user.GetALlKeyArray()
}

func DeleteOUser(userid string, value interface{}) {
	user.DeleteOUser(userid,value)
}

func GetSetOneUser(userid string, value interface{})interface{}{
	v,ok:=user.GetSetOneUser(userid,value)
	if ok&& filterlist.Len() > 0 {
		log.Debug("添加新用户",userid,"进入过滤器")
		for e := filterlist.Front(); e != nil; e = e.Next() {
			fh, ok := e.Value.(*FilterHandlerFunc)
			if ok {
				fh.addHandlerFunc(userid, value)
			}
		}
	}
	return v
}

func DeleteUser(userid string, value interface{}) {
	if len(userid) > 0 {
		cl,t:= user.DeleteUser(userid, value)
		if cl && filterlist.Len() > 0 {

			log.Debug("删除用户",userid,"进入过滤器")

			for e := filterlist.Front(); e != nil; e = e.Next() {
				fh, ok := e.Value.(*FilterHandlerFunc)
				if ok {
					fh.deleteHandlerFunc(userid, value,t)
				}
			}
		}
	}

}

func DeleteValue(value interface{}) {
	user.DeleteValue(value)
}
